<template>
  <div>
    <el-card
      class="box-card"
      shadow="hover"
      style="margin-top: 60px; margin-bottom: 20px"
    >
      <el-row style="margin-bottom: 20px">
        <el-col :span="2">
          <div class="block">
            <span class="demonstration"></span>
            <el-cascader
              v-model="optType"
              :options="options"
              @change="handleChange"
              placeholder="商品分类"
            ></el-cascader>
          </div>
        </el-col>
        <el-col :span="3" :offset="1">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker
              v-model="optTime"
              type="datetimerange"
              start-placeholder="商品创建日期"
              end-placeholder="日期"
              :default-time="['12:00:00']"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="optTimeHandle"
            >
            </el-date-picker>
          </div>
        </el-col>
        <el-col :span="1" :offset="5" style="width: 5%; margin-top: 10px"
          >累计销量</el-col
        >
        <el-col :span="2">
          <el-input
            placeholder="请输入"
            v-model="selByCondition.cumulativeSalesL"
            clearable
          >
          </el-input>
        </el-col>
        <el-col :span="1" style="margin-top: 10px; width: 2%">至</el-col>
        <el-col :span="2" :offset="0">
          <el-input
            placeholder="请输入"
            v-model="selByCondition.cumulativeSalesG"
            clearable
          >
          </el-input>
        </el-col>
        <el-col :span="1" :offset="1" style="width: 4%; margin-top: 10px"
          >库存量</el-col
        >
        <el-col :span="2">
          <el-input
            placeholder="请输入"
            v-model="selByCondition.stockL"
            clearable
          >
          </el-input>
        </el-col>
        <el-col :span="1" style="margin-top: 10px; width: 2%">至</el-col>
        <el-col :span="2" :offset="0">
          <el-input
            placeholder="请输入"
            v-model="selByCondition.stockG"
            clearable
          >
          </el-input>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">
          <el-input
            placeholder="商品名称"
            v-model="selByCondition.productName"
            clearable
          >
          </el-input>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-input
            placeholder="商品编码"
            v-model="selByCondition.productId"
            clearable
          >
          </el-input>
        </el-col>
        <el-col :span="1" :offset="1" style="width: 6%; margin-top: 10px"
          >当前售价：</el-col
        >
        <el-col :span="2">
          <el-input
            placeholder="请输入"
            v-model="selByCondition.priceL"
            clearable
          >
          </el-input>
        </el-col>
        <el-col :span="1" style="margin-top: 10px; width: 2%">至</el-col>
        <el-col :span="2" :offset="0">
          <el-input
            placeholder="请输入"
            v-model="selByCondition.priceG"
            clearable
          >
          </el-input>
        </el-col>
        <el-col :span="1" :offset="1">
          <el-button
            icon="el-icon-search"
            circle
            style="font-size: 15px"
            @click="selInfo"
          ></el-button>
        </el-col>
        <el-col :span="1">
          <el-button
            type="info"
            icon="el-icon-refresh"
            circle
            @click="cleanCondition"
          ></el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-row>
      <el-col :span="10">
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
        >
          <el-menu-item index="">全部</el-menu-item>
          <el-menu-item index="1">下架</el-menu-item>
          <el-menu-item index="2">上架</el-menu-item>
          <el-menu-item index="3">已售罄</el-menu-item>
        </el-menu>
      </el-col>
    </el-row>
    <el-row style="margin-top: 10px; margin-bottom: 10px">
      <el-col :span="2">
        <i class="el-icon-tickets" style="color: #454545">商品列表</i>
      </el-col>
      <el-col :span="2">
        <el-button size="mini" @click="deleteProduct" icon="el-icon-delete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="2">
        <el-button size="mini" icon="el-icon-top" @click="exportInfo"
          >导出</el-button
        >
      </el-col>
      <el-col :span="2" :offset="14">
        <el-button size="mini" icon="el-icon-plus" @click="showAddDialog"
          >新增</el-button
        >
      </el-col>
      <el-col :span="2" :offset="0">
        <el-button size="mini" icon="el-icon-upload2" @click="productPush"
          >商品推送</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-table
          id="table_excel"
          :data="tableData"
          border
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column prop="" label="" type="selection"> </el-table-column>
          <el-table-column prop="id" label="商品编码" width="180">
          </el-table-column>
          <el-table-column prop="name" label="商品信息" width="180">
          </el-table-column>
          <el-table-column prop="productImg" label="商品封面" width="180">
            <template slot-scope="scope">
              <img
                v-if="scope.row.productImg"
                :src="scope.row.productImg"
                class="avatar"
                style="width: 120px; height: 120px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="当前售价"> </el-table-column>
          <el-table-column prop="stock" label="库存量"> </el-table-column>
          <el-table-column prop="cumulativeSales" label="累计销量">
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
          </el-table-column>
          <el-table-column prop="status" label="商品状态">
            <template slot-scope="scope">
              {{ changeStatus(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作">
            <template slot-scope="scope">
              <el-link type="primary" @click="putaway(scope.row.id)"
                >上架</el-link
              >&nbsp;
              <el-link type="primary" @click="soldOut(scope.row.id)"
                >下架</el-link
              >&nbsp;
              <el-link type="primary" @click="updateProduct(scope.row.id)"
                >编辑</el-link
              >&nbsp;
              <!-- <el-link type="primary">查看详情</el-link> -->
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 分页 -->
    <el-row>
      <el-col :span="7" :offset="15">
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[2, 4, 5, 8, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @next-click="nextPage"
            @prev-click="prevPage"
          >
          </el-pagination>
        </div>
      </el-col>
    </el-row>

    <!-- 添加框 -->
    <el-dialog
      :title="dialogMsg"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span></span>
      <el-row style="margin-bottom: 10px">
        <el-col :span="10">
          <div class="block">
            <span class="demonstration"></span>
            <el-cascader
              v-model="optType"
              :options="options"
              @change="handleAddArgs"
              placeholder="选择类别"
            ></el-cascader>
          </div>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="10">
          <el-input
            placeholder="商品编号"
            v-model="addParams.productId"
            clearable
          >
          </el-input>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="10">
          <el-input
            placeholder="商品名称"
            v-model="addParams.productName"
            clearable
          >
          </el-input>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="10">
          <el-input placeholder="商品单价" v-model="addParams.price" clearable>
          </el-input>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="10">
          <el-input placeholder="现有库存" v-model="addParams.stock" clearable>
          </el-input>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="4"> 封面图： </el-col>
        <el-col :span="10">
          <el-upload
            class="avatar-uploader"
            action="api/scss-server/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="header"
          >
            <img v-if="coverImgUrl" :src="coverImgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-col :span="4"> 详情图片： </el-col>
        <el-col :span="10">
          <el-upload
            class="avatar-uploader"
            action="api/scss-server/upload"
            :show-file-list="true"
            :on-success="handleImgListSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="header"
            multiple
            :limit="5"
            :file-list="fileList"
            list-type="picture-card"
            :on-remove="handleRemove"
          >
            <!-- <div v-for="item in showImgList" :key="item.id">
              <img v-if="item" :src="item" class="avatar" />
            </div> -->
            <!-- <img v-if="fileList" :src="fileList" class="avatar" /> -->
            <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
          </el-upload>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="addProduct">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.selProductSort();
    this.selProductByCondition();
  },
  data() {
    return {
      addOrUpdate: 0, // 添加1，修改2
      showImgList: [],
      fileList: [],
      header: {
        token: localStorage.getItem("token"),
      },
      addParams: {
        productTypeParentId: "",
        productTypeId: "",
        productId: "",
        productName: "",
        price: "",
        stock: "",
        productImg: "",
        imgList: [],
      },
      coverImgUrl: "",
      dialogMsg: "",
      dialogVisible: false,
      deleteList: [],
      activeIndex: "",
      optTime: [],
      tableData: [],
      optType: [],
      options: [],
      selByCondition: {
        productId: "",
        productTypeId: "",
        productTypeParentId: "",
        createTimeStart: "",
        createTimeEnd: "",
        cumulativeSalesG: "",
        cumulativeSalesL: "",
        priceG: "",
        priceL: "",
        productName: "",
        stockG: "",
        stockL: "",
        productStatus: "",
      },
      pageNum: 1,
      pageSize: 5,
      total: null,
    };
  },
  methods: {
    productPush() {
      this.$axios.get("api/scss-server/productPush").then((response) => {
        if (response.data.code == 200) {
          this.$message({
            showClose: true,
            message: "同步推送成功",
            type: "success",
          });
        }
      });
    },
    handleRemove(file) {
      //console.log(this.addParams.imgList);
      for (let i = 0; i < this.addParams.imgList.length; i++) {
        if (this.addParams.imgList[i] == file.name) {
          this.addParams.imgList.splice(i, 1);
          break;
        }
      }
      //console.log(this.addParams.imgList);
    },
    closeDialog() {
      this.optType = [];
      this.dialogVisible = false;
    },
    updateProduct(productId) {
      this.addOrUpdate = 2;
      //console.log(productId);
      this.fileList = [];
      this.dialogVisible = true;
      this.$axios
        .get("api/scss-server/selProductById", {
          params: { productId: productId },
        })
        .then((response) => {
          if (response.data.code == 200) {
            this.addParams.productId = productId;
            this.addParams.productName = response.data.data.name;
            this.addParams.price = response.data.data.price;
            this.addParams.stock = response.data.data.stock;
            this.coverImgUrl = response.data.data.productImg;
            this.addParams.productImg = response.data.data.productImg;
            this.fileList = [];
            this.addParams.imgList = [];
            response.data.data.imgLists.forEach((e) => {
              let imgSrc = {};
              imgSrc.name = e.imgSrc;
              imgSrc.url = e.imgSrc;
              this.fileList.push(imgSrc);
              // console.log(e.imgSrc);
              this.addParams.imgList.push(e.imgSrc);
            });
            //console.log(this.options);
            this.optType = [
              response.data.data.parentId,
              response.data.data.productTypeId,
            ];
            this.addParams.productTypeParentId = this.optType[0];
            this.addParams.productTypeId = this.optType[1];
          }
        });
    },
    exportInfo() {
      this.$confirm("确定要导出当页件到Excel?", "导出提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(() => {
          setTimeout(() => {
            var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
            let tables = document.getElementById("table_excel"); //这里是绑定元素，输入你要导出的table表格的id
            let table_book = this.$XLSX.utils.table_to_book(tables, xlsxParam);
            const table_write = this.$XLSX.write(table_book, {
              bookType: "xlsx",
              bookSST: true,
              type: "array",
            });
            try {
              this.$FileSaver.saveAs(
                new Blob([table_write], { type: "application/octet-stream" }),
                `${this.title}.xlsx` //这里是文件名
              );
            } catch (e) {
              if (typeof console !== "undefined") console.log(e, table_write);
            }
            return table_write;
          }, 1000);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消导出",
          });
        });
    },
    addProduct() {
      //console.log(this.addParams);
      if (this.addOrUpdate == 1) {
        // 添加
        // 添加
        this.$axios
          .post("api/scss-server/addProduct", this.addParams)
          .then((response) => {
            if (response.data.code == 200) {
              this.dialogVisible = false;
              this.selInfo();
              this.$message({
                message: "添加成功！",
                type: "success",
              });
            }else{
              console.log(response.data.data);
            }
            // console.log(response.data);
          });
      } else if (this.addOrUpdate == 2) {
        // 修改
        //console.log(this.addParams);
        this.$axios
          .post("api/scss-server/updateProduct", this.addParams)
          .then((response) => {
            if (response.data.code == 200) {
              this.dialogVisible = false;
              this.selInfo();
              this.optType = [];
              this.$message({
                showClose: true,
                message: "修改成功",
                type: "success",
              });
            }
          });
      }
    },
    handleImgListSuccess(response, file, fileList) {
      // console.log("上传成功:");
      // console.log(response);
      // console.log(file);
      // console.log(fileList);
      this.showImgList.push(response.data);
      this.addParams.imgList = this.showImgList;
    },
    handleClose() {},
    handleAddArgs() {
      this.addParams.productTypeParentId = this.optType[0];
      this.addParams.productTypeId = this.optType[1];
    },
    beforeAvatarUpload() {},
    handleAvatarSuccess(response) {
      if (response.code == 200) {
        this.coverImgUrl = response.data;
        this.addParams.productImg = response.data;
      }
    },
    showAddDialog() {
      this.fileList = [];
      // this.addParams.imgList = [];
      //this.showImgList = [];
      this.addOrUpdate = 1;
      this.coverImgUrl = "";
      this.showImgList = [];
      this.optType = [];
      this.addParams = {
        productTypeParentId: "",
        productTypeId: "",
        productId: "",
        productName: "",
        price: "",
        stock: "",
        productImg: "",
        imgList: [],
      };
      this.dialogVisible = true;
      this.dialogMsg = "添加新的商品";
    },
    deleteProduct() {
      if (this.deleteList.length == 0) {
        this.$message({
          message: "请选择一项进行删除",
          type: "warning",
        });
        return;
      }

      let pageParam = {};
      pageParam.param = [];

      for (let index = 0; index < this.deleteList.length; index++) {
        pageParam.param.push(this.deleteList[index]);
      }

      this.$axios
        .post("api/scss-server/deleteProduct", pageParam)
        .then((response) => {
          if (response.data.code == 200) {
            this.selInfo();
            this.$message({
              message: "删除成功",
              type: "success",
            });
          }
        });
    },
    handleSelectionChange(val) {
      console.log(val);
      this.deleteList = val;
    },
    soldOut(id) {
      this.$axios
        .get("api/scss-server/soldOut", { params: { id: id + "" } })
        .then((response) => {
          // console.log(response.data);
          if (response.data.code == 200) {
            this.selInfo();
            this.$message({
              message: "下架成功",
              type: "success",
            });
          } else if (response.data.code == 609) {
            this.$message({
              message: "已经下架！",
              type: "warning",
            });
          }
        });
    },
    putaway(id) {
      // console.log(id);
      this.$axios
        .get("api/scss-server/putaway", { params: { id: id + "" } })
        .then((response) => {
          // console.log(response.data);
          if (response.data.code == 200) {
            this.selInfo();
            this.$message({
              message: "上架成功",
              type: "success",
            });
          } else if (response.data.code == 608) {
            this.$message({
              message: "已经上架！",
              type: "warning",
            });
          }
        });
    },
    changeStatus(num) {
      if (num == 1) {
        return "下架";
      } else if (num == 2) {
        return "上架";
      } else if (num == 3) {
        return "售罄";
      }
    },
    cleanCondition() {
      this.optTime = [];
      this.optType = [];
      this.selByCondition = {
        productId: "",
        productTypeId: "",
        productTypeParentId: "",
        createTimeStart: "",
        createTimeEnd: "",
        cumulativeSalesG: "",
        cumulativeSalesL: "",
        priceG: "",
        priceL: "",
        productName: "",
        stockG: "",
        stockL: "",
        productStatus: "",
      };
    },
    prevPage(val) {
      this.pageNum = val;
      this.selProductByCondition();
    },
    nextPage(val) {
      this.pageNum = val;
      this.selProductByCondition();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.selProductByCondition();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.selProductByCondition();
    },
    handleSelect(key, keyPath) {
      //   console.log(key);
      this.selByCondition.productStatus = key;
      this.selInfo();
    },
    optTimeHandle() {
      //   console.log(this.optTime);
      this.selByCondition.createTimeStart = this.optTime[0];
      this.selByCondition.createTimeEnd = this.optTime[1];
    },
    convertDataToOptions(data) {
      const topLevelOptions = {};
      const allOptions = {};

      data.forEach((item) => {
        const option = {
          value: item.id,
          label: item.typeName,
        };

        // 如果是顶级菜单，直接添加到顶层选项
        if (item.parentId === "-1") {
          topLevelOptions[item.id] = option;
        }

        // 存储所有选项，包括非顶级选项
        allOptions[item.id] = option;

        // 如果不是顶级菜单，找到父级并添加到其 children 中
        if (allOptions[item.parentId]) {
          if (!allOptions[item.parentId].children) {
            allOptions[item.parentId].children = [];
          }
          allOptions[item.parentId].children.push(option);
        }
      });

      // 将顶层选项转换为数组
      const result = Object.values(topLevelOptions);

      // 删除没有子元素的空 children 数组
      result.forEach((option) => {
        if (option.children && option.children.length === 0) {
          delete option.children;
        }
      });

      return result;
    },

    selProductSort() {
      this.$axios.get("api/scss-server/selProductSort").then((response) => {
        if (response.data.code == 200) {
          //   console.log(response.data);
          let result = this.convertDataToOptions(response.data.data);
          // console.log(result);
          this.options = result;
        }
      });
    },
    selInfo() {
      this.pageNum = 1;
      this.selProductByCondition();
    },
    selProductByCondition() {
      // console.log("查询参数");
      // console.log(this.selByCondition);
      let params = {};
      params.pageNum = this.pageNum;
      params.pageSize = this.pageSize;
      params.param = this.selByCondition;

      this.$axios
        .post("api/scss-server/selProductByCondition", params)
        .then((response) => {
          if (response.data.code == 200) {
            // console.log(response.data.data.list);
            this.pageNum = response.data.data.pageNum;
            this.total = response.data.data.total;
            this.pageSize = response.data.data.pageSize;
            this.tableData = response.data.data.list;
          }
        });
    },
    handleChange() {
      // console.log(this.optType);
      this.selByCondition.productTypeParentId = this.optType[0];
      this.selByCondition.productTypeId = this.optType[1];
      this.selInfo();
    },
  },
};
</script>

<style scoped>
/*################## element ui ###############*/
.avatar-uploader-icon {
  border-radius: 5px;
  border: 1px dashed #8c939d;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar-uploader-icon:hover {
  border: 1px dashed #409eff;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
